<?php

namespace Rblog\Module\Admin\Model;

class Artsort extends \Rexzy\App\Model {
    
    protected $_table = 'artsort';
    
    /**
     * 添加分类
     * 
     * @param string $name 分类名
     * @param string $slugname 缩略名
     * @param int $parentsort 父分类
     * @param string $describe 分类描述
     * @return boolean 添加分类是否成功
     */
    public function add( $name, $slugname, $parent, $describe ) {
        $data = array(
            'name' => $name,
            'slugname' => $slugname,
            'parent' => $parent,
            'children' => 0,
            'arts' => 0,
            'description' => $describe,
        );
        
        $result = $this->insert( $data );
        if ( $result > 0 ) {
            if ( $parent != 0 ) {
                $sql = "update rblog_artsort set children = children + 1 where sortid = $parent";
                $this->query( $sql );
            }
            return true;
        }
        return false;
    }
    
    /**
     * 检查是否已经存在某个分类或缩略名
     * 
     * @param string $filed 检查的表字段
     * @param string $val 是否存在的值
     * @return boolean 查询结果，已存在返回id，否返回false
     */
    public function check( $key, $val ) {
        $where = "where $key = '$val'";
        $result = $this->select( 'sortid', $where );
        if ( count( $result ) != 0 ) {
            return $result['sortid'];
        }
        return false;
    }
    
    /**
     * 更改分类包含的子类数量
     * 
     * @param int $sortid 变化的分类id
     * @param string $price -1：子类减去1个 ， +1：子类加1个
     */
    public function childChange( $sortid, $price ) {
        $sql = "update rblog_artsort set children = children " . $price . " where sortid = " . $sortid;
        $this->query($sql);
    }
    
    /**
     * 擦除文章分类
     * 
     * @param array $sortid 擦除的分类id
     * @return int 擦除的行数
     */
    public function delsort( $sortid ) {
        $wherestr = array();
        foreach ( $sortid as $key => $value ) {
            $sortMesg = $this->select( 'children, parent', "where sortid = $value" );
            if ( $sortMesg['parent'] != 0 ){
                $this->childChange( $sortMesg['parent'], '- 1' );
            }
            if ( $sortMesg['children'] != 0 ) {
                $children = $this->selectAll( 'sortid', "where parent = $value" );
                foreach( $children as $key1 => $value1 ) {
                    $this->update( array( 'parent' => $sortMesg['parent'] ), "sortid = ".$value1['sortid'] );
                    if ( $sortMesg['parent'] != 0 ) {
                        $this->childChange( $sortMesg['parent'], '+ 1' );
                    }
                }
            }
            
            $wherestr[] = 'sortid = ' . trim( $value );
        }
        
        $where = implode( ' or ', $wherestr );
        
        $result = $this->delete( $where );
        return $result;
    }
}

